var APP = require("../../../lib/main/app");
var page = {
	countdown:30,
	examId:0,//考试id
	categoryId:'',//科目id
	deviceId:'test',//设备id
	testData:null,//开始考试数据
	isreturn:true,//是否可以退出考试
	code:'',//科目
	timeObj:{
		hour:0,
		minute:0,
		second:0,
		millisecond:0,
	},
	interval:null,//倒计时
	objArr: [{type:'0x00',typeName : '镜下识别'},{type:'0x01',typeName : '夹持训练'},{type:'0x02',typeName : '定位摆放'},{type:'0x03',typeName : '飞跃龙门'},{type:'0x04',typeName : '剪切训练'},{type:'0x05',typeName : '缝合训练'}],
	operation:[],
	isEnterTest:false,
	typeName:'',
	threadError:false,//是否触发错误
	threadTrigger:false,//记录飞越龙门是否开始
	threadTimes: null,//倒计时
	useTimes:0,//考试用时
	redBall:0,//红球
	greenBall:0,//绿球
	ballCensus:true,//限制短时间增加次数
	metalBallCensus:true,//限制短时间增加次数
	lang:'cn',
	ready: function() {
		var that = this;
		try{
			let lang =  api.getGlobalData({key: 'lang'}) || 'cn';
			that.lang = lang;
			i18n("[i18n]", {
				lang: lang,// 变更语言
				filePath: "i18n/",
				get: true
			});
			if(lang == 'en'){
				$('.test-tc-top').addClass('test-tc-en');
			}
		}catch(e){
			//TODO handle the exception
		}
		that.examId = api.pageParam.examId;
		that.categoryId = api.pageParam.categoryId;
		that.code = api.pageParam.code;
		that.typeName = api.pageParam.typeName;
		that.deviceId = api.pageParam.deviceId ? api.pageParam.deviceId : 'test';
		$('.clamp-switch').removeClass('close').removeClass('on');
		for (var i = 0; i < that.objArr.length; i++) {
			if(that.objArr[i].type == that.code){
				if(!that.typeName){
					that.typeName = that.objArr[i].typeName;
					$('.header-box .name').text(that.typeName);
				}
				switch (that.code){
					case '0x00':
						$('.microscopic').show();
						break;
					case '0x01':
						$('.clamp').show();
						break;
					case '0x02':
						$('.ferrule').show();
						break;
					case '0x03':
						$('.thread').show();
						break;
					case '0x04':
						$('.shear').show();
						break;
					case '0x05':
						$('.suture').show();
						break;
					default:
						break;
				}
				break;
			}
		}
		// 头部处理
		var headerHeight = $('#header').height();
		$('body').css('padding-top', headerHeight);
	},
	on: function() {
		var that = this;
		// 已进入考试页面
		// 进入测试页面才打开开关
		api.sendEvent({
			name: 'isEnterTest',
			extra: {
				isEnterTest: true,
			}
		});
		// 测试数据弹窗
		// api.addEventListener({
		// 	name: 'receiveDataOld'
		// },function(ret, err) {
		// 	var data = '<li>' + ret.value.receiveDataOld + '</li>';
		// 	$('.data-box-ul').prepend(data)
		// 	if($('.data-box-ul li').length > 500){
		// 		$('.data-box-ul li').last().remove()
		// 	}
		// });
		
		// 监听数据给予反馈
		api.addEventListener({
			name: 'animation'
		},function(ret, err) {
			try{
				var animationData = ret.value.animationData;
				// 开关判断
				if(animationData.switch_state == 'open'){
					$('.clamp-switch').removeClass('close').addClass('on');
					if(!that.isEnterTest){
						that.isEnterTest = true;
						that.enterTest();//进入考试练习
					}
				}else if(animationData.switch_state == 'wait' && !animationData.isError){
					$('.clamp-switch').removeClass('close').removeClass('on');
				}
				// 开始
				switch (animationData.type){
					// 镜下识别
					case 'microscopic':
						that.microscopic(animationData);
						break;
					// 夹持训练
					case 'clamp':
						that.clamp(animationData.data);
						break;
					// 定位摆放
					case 'ferrule':
						that.ferrule(animationData);
						break;
					// 飞跃龙门
					case 'thread':
						that.thread(animationData);
						break;
					// 剪切训练
					case 'shear':
						that.shear(animationData.data);
						break;
					// 缝合训练
					case 'suture':
						that.suture(animationData);
						break;
					default:
						break;
				}
				
			}catch(e){
				//TODO handle the exception
			}
		});
		// 监听考试结束
		api.addEventListener({
			name: 'TEST_OVER'
		},function(ret, err) {
			var testData = ret.value.testData;
			that.subTest(testData);
		});
		
		// 监听是否换手操作
		api.addEventListener({
			name: 'CHANGE_HAND'
		},function(ret, err) {
			let toast = i18n.get("chang.hand.invalid") || '换手操作无效';
			API.errorToast(toast);
		});
		

		//监听返回
		API.listenEvt('keyback', function() {
			let toast = i18n.get("finish.exam") || '正在考试中,请先结束考试';
			if(that.isreturn){
				api.sendEvent({
					name: 'isEnterTest',
					extra: {
						isEnterTest: false,
					}
				});
				APP.w.closeWin();
			}else{
				API.errorToast(toast);
			}
		});
		//批量事件start
		var events = [
			//打开页面
			['#add-channel', function() {

			}],
			// 关闭页面
			['#close', function() {
				if(that.isreturn){
					api.sendEvent({
						name: 'isEnterTest',
						extra: {
							isEnterTest: false,
						}
					});
					APP.w.closeWin();
				}else{
					let toast = i18n.get("finish.exam") || '正在考试中,请先结束考试';
					API.errorToast(toast);
				}
			}],
			
		];
		APP.e.more(events);
		//批量事件end
	},
	methods: {
		// 镜下识别
		microscopic: function(animationData){
			let that = this;
			// console.log(JSON.stringify(animationData)+'----------')
			let data = animationData.data;
			// 正确
			for (let i = 0; i < animationData.rightNum; i++) {
				$('.microscopic .microscopic-lis').eq(i).addClass('success');
			}
			// 错误
			for (let i = animationData.rightNum; i < 5; i++) {
				if(data[i+1] == 1){
					// console.log('执行+'+i)
					let index = i;
					$('.microscopic .microscopic-lis').eq(i).addClass('fail');
					setTimeout(function(){
						// console.log('镜下识别+'+i)
						$('.microscopic .microscopic-lis').eq(i).removeClass('fail');
					},800,i);
					break;
				}
			}
		},
		// 夹持训练
		clamp: function(data){
			var that = this;
			// console.log(JSON.stringify(data)+'----------')
			$('.clamp-switch').addClass('on');

			// 红色左侧 绿色右侧
			if(data[1] == 1 ){
				// 红色球
				if(that.ballCensus){
					that.ballCensus = false;
					that.redBall = that.redBall + 1;
					var _num = 10 - that.redBall > 0 ? 10 - that.redBall : 0;
					$('.clamp-num .left span').text(_num);
					if(_num < 1){
						$('.clamp-txt .left span').show();
					}
					setTimeout(function(){
						that.ballCensus = true;
					},200)
				}
			}else if(data[2] == 1){
				$('.clamp-fail').show();
				setTimeout(function(){
					$('.clamp-fail').hide();
				},800)
			}
			if(data[4] == 1 && that.redBall >= 10){
				// 绿色球
				if(that.metalBallCensus){
					that.metalBallCensus = false;
					that.greenBall = that.greenBall + 1;
					var _num = 10 - that.greenBall > 0 ? 10 - that.greenBall : 0;
					$('.clamp-num .right span').text(_num);
					if(_num < 1){
						$('.clamp-txt .right span').show();
					}
					setTimeout(function(){
						that.metalBallCensus = true;
					},200)
				}
			}else if(data[3] == 1 || data[4] == 1){
				$('.clamp-fail2').show();
				setTimeout(function(){
					$('.clamp-fail2').hide();
				},800)
			}
			// 发送数据
			// 监听球数据
			// console.log('redBall:'+that.redBall)
			// console.log('greenBall:'+that.greenBall)
			api.sendEvent({
				name: 'ball',
				extra: {
					redBall: that.redBall,
					greenBall: that.greenBall,
				}
			});
		},
		// 定位摆放
		ferrule: function(animationData){
			var that = this;
			// console.log(JSON.stringify(animationData)+'----------')
			var data = animationData.data;
			if(animationData.switch_state != 'open' && animationData.isError){
				// 未开始就有信号
				$('.clamp-switch').addClass('close');
				for (let i = 0; i < data.length; i++) {
					if(data[i + 1] == 1 ){
						$('.ferrule .ferrule-lis').eq(i).removeClass('success').addClass('fail');
					}else{
						$('.ferrule .ferrule-lis').eq(i).removeClass('success').removeClass('fail')
					}
				}
			}else{
				$('.clamp-switch').addClass('on');
				// 正确
				let rightNum = animationData.rightNum;//获取有几个正确的
				for (let i = 0; i < rightNum; i++) {
					$('.ferrule .ferrule-lis').eq(i).removeClass('fail').addClass('success');
				}
				// 错误
				for (let i = rightNum; i < data.length; i++) {
					if(data[i + 1] == 1 ){
						$('.ferrule .ferrule-lis').eq(i).removeClass('success').addClass('fail');
					}else{
						$('.ferrule .ferrule-lis').eq(i).removeClass('success').removeClass('fail')
					}
				}
			}
		},
		// 飞跃龙门
		thread: function(animationData){
			var that = this;
			let data = animationData.data
			let data2 = animationData.data2
			$('.clamp-switch').addClass('on');
			// 6根柱子依次穿过20240229
			// for (var i = 0; i < data.length; i++) {
			// 	if(data[i + 1] == 1 ){
			// 		$('.thread .thread-lis').eq(i).addClass('success');
			// 	}else{
			// 		$('.thread .thread-lis').eq(i).removeClass('success');
			// 	}
			// }
			if(data[1] == 1  && that.threadTrigger){
				$('.thread .thread-lis').eq(0).addClass('success');
			}
			if(data[2] == 1 ){
				that.threadTrigger = true;
				$('.thread .thread-lis').eq(1).addClass('success');
			}
			// 碰到铁丝&& !that.threadError 
			if(data[3] == 1 && (data2[6] == 1 || data2[7] == 1) && animationData.threadError){
				that.threadError = true;
				$('.thread .thread-lis').eq(2).addClass('fail');
				if(that.threadTimes){
					clearTimeout(that.threadTimes)
				}
				that.threadTimes = setTimeout(function(){
					$('.thread .thread-lis').eq(2).removeClass('fail');
				},380)
				setTimeout(function(){
					that.threadError = false;
				},400)
			}
		},
		// 剪切训练
		shear: function(data){
			var that = this;
			$('.clamp-switch').addClass('on');
			// 有剪切超界信号  fail1触发边界，fail2触发内部
			// 内边界 
			if(data[1] == 1){
				$('.shear .shear-lis').addClass('fail2');
				setTimeout(function(){
					$('.shear .shear-lis').removeClass('fail2');
				},800)
			}
			// 外边界
			if(data[2] == 1){
				$('.shear .shear-lis').addClass('fail1');
				setTimeout(function(){
					$('.shear .shear-lis').removeClass('fail1');
				},800)
			}
		},
		// 缝合训练
		suture: function(animationData){
			var that = this;
			$('.clamp-switch').addClass('on');
			// 正确
			let data = animationData.data;
			let isOrder = animationData.isOrder;//按顺序
			// console.log(JSON.stringify(animationData)+'----------')
			if(isOrder){
				// 按顺序
				let rightNum = animationData.rightNum;//获取有几个正确的
				for (let i = 0; i < rightNum; i++) {
					$('.suture .suture-lis').eq(i).addClass('success').removeClass('fail');
				}
				// 错误
				for (let i = rightNum; i < data.length; i++) {
					if(data[i + 1] == 1){
						$('.suture .suture-lis').eq(i).removeClass('success').addClass('fail');
					}else{
						$('.suture .suture-lis').eq(i).removeClass('success').removeClass('fail')
					}
				}
			}else{
				for (var i = 0; i < 3; i++) {
					if(data[i+1] == 1){
						$('.suture .suture-lis').eq(i).addClass('success').removeClass('fail');
					}else{
						$('.suture .suture-lis').eq(i).removeClass('success').removeClass('fail')
					}
				}
			}
		},
		checkTime: function(i){ //将0-9的数字前面加上0，例1变为01 
			if(i < 10) {
				i = "0" + i;
			}
			return i;
		},
		// 开始考试
		enterTest: function(){
			var that = this;
			var params = {
				exam_id: that.examId,//考试id 如果是练习直接传0
				category_id: that.categoryId,//考试科目
				device_id: that.deviceId,//设备id
			}
			APP.r.post({
				api: 'exam/join_exam_log',
				params:params,
				success: function(res) {
					that.testData = res.data;
					that.isreturn = false;//开始考试不允许退出
					that.intervalTime();
				}
			});
		},
		// 开始考试倒计时
		intervalTime: function(){
			var that = this;
			that.useTimes = 0;
			// 开始计时
			var hour, minute, second , millisecond; //时 分 秒 毫秒
			hour = that.timeObj.hour;
			minute = that.timeObj.minute;
			second = that.timeObj.second;
			millisecond = that.timeObj.millisecond; //毫秒
			try{
				clearInterval(that.interval)
			}catch(e){
				//TODO handle the exception
			}
			that.interval = setInterval(() => {
				that.useTimes += 1;
				millisecond = millisecond + 1000;
				if (millisecond >= 1000) {
					millisecond = 0;
					second = second + 1;
				}
				if (second >= 60) {
					second = 0;
					minute = minute + 1;
				}
				if (minute >= 60) {
					minute = 0;
					hour = hour + 1;
				}
				// 发送时间
				api.sendEvent({
					name: 'useTimes',
					extra: {
						useTimes: that.useTimes,
					}
				});
				var minute1 = minute > 9 ? minute :'0' + minute
				var second1 = second > 9 ? second :'0' + second
				var hour1 = hour > 9 ? hour :'0' + hour
				if(hour > 0 ){
					var remaining = hour1  +':'+ minute1 +':'+ second1
				}else{
					var remaining = minute1 +':'+ second1
				}
				// 时间到了
				if (that.code == '0x00' || that.code == '0x01' || that.code == '0x02') {
					if(that.useTimes > 90){
						// 到时间结束考试
						api.sendEvent({
							name: 'time_end',
							extra: {}
						});
						clearInterval(that.interval)
						return false;
					}
				}else if(that.code == '0x03'){
					// 飞跃龙门
					if(that.useTimes > 600){
						// 到时间结束考试
						api.sendEvent({
							name: 'time_end',
							extra: {}
						});
						clearInterval(that.interval)
						return false;
					}
				}else if(that.code == '0x04'){
					// 剪切 
					if(that.useTimes > 150){
						// 到时间结束考试
						api.sendEvent({
							name: 'time_end',
							extra: {}
						});
						clearInterval(that.interval)
						return false;
					}
				}else if(that.code == '0x05'){
					//  缝合
					if(that.useTimes > 180){
						// 到时间结束考试
						api.sendEvent({
							name: 'time_end',
							extra: {}
						});
						clearInterval(that.interval)
						return false;
					}
				}
				$('.test-time i').text(remaining)
			},1000)
		},
		//倒计时自动到首页
		rest: function(){
			var that = this;
			setInterval(function(){
				var totalTime = that.countdown; //总秒钟
				if(totalTime > 0) {
					totalTime--;
					that.countdown = totalTime
				}
				if(that.countdown > 0){
					let _txt1 = i18n.get("count.down") || '倒计时';
					let _txt2 = i18n.get("auto.jump") || '自动跳转到首页';
					$('.test-tc-time').html(`<p> ${_txt1} <span> ${that.countdown}s </span> ${_txt2}</p>`)
				}else{
					api.sendEvent({
						name: 'isEnterTest',
						extra: {
							isEnterTest: false,
						}
					});
					APP.w.closeWin();
				}
			},1000)
		},
		// 考试完弹窗
		testEnd: function(data) {
			var that = this;
			$('.clamp-switch').addClass('close');//开关关闭
			that.isreturn = true;
			clearInterval(that.interval)//清除考试结果
			that.rest();//倒计时进入首页
			let _txt1 = i18n.get("operation.score") || '操作分';
			let _txt2 = i18n.get("time.score") || '时间分';
			let _txt3 = i18n.get("total.score") || '总分';
			let _txt4 = i18n.get("score") || '分';
			let _txt5 = i18n.get("touch.error") || '触碰错误';
			let _txt6 = i18n.get("times") || '次';
			let _txt7 = i18n.get("left.touch.error") || '左手触碰错误';
			let _txt8 = i18n.get("right.touch.error") || '右手触碰错误';
			let _txt9 = i18n.get("left.operate") || '左手操作';
			let _txt10 = i18n.get("right.operate") || '右手操作';
			let extend = JSON.parse(data.extend);
			var _html = ''
			if(data.type == '0x03'){
				_html = `<div class="test-tc-lis">
							<span>${data.errorTimes}<i>${_txt6}</i></span>
							<p>${_txt5}</p>
						</div>`
			}
			_html = _html + `<div class="test-tc-lis">
							<span>${data.do_point} <i>${_txt4}</i></span>
							<p>${_txt1}</p>
						</div>
						<div class="test-tc-lis">
							<span>${data.time_point} <i>${_txt4}</i></span>
							<p>${_txt2}</p>
						</div>
						<div class="test-tc-lis">
							<span>${data.point} <i>${_txt4}</i></span>
							<p>${_txt3}</p>
						</div>`
			$('.test-tc-bottom').html(_html);

			// 操作部位
			var _operateHtml = ''
			
			if(that.code == '0x03'){
				// 飞跃龙门
				_operateHtml =  `
				<div class="operate-lis">${_txt7}：<span>${data.leftErrorTimes}</span> ${_txt6}</div>
				<div class="operate-lis">${_txt8}：<span>${data.rightErrorTimes}</span> ${_txt6}</div>`
			}else{
				if(extend.hand == 'left'){
					_operateHtml =  `<div class="operate-lis"><span>${_txt9}</span></div>`
				}else if(extend.hand == 'right'){
					_operateHtml =  `<div class="operate-lis"><span>${_txt10}</span></div>`
				}
			}
			$('.test-tc-txt .operate').html(_operateHtml);
			if(data.point < 60){
				$('.test-tc-con').addClass('test-tc-fail');
			}
			$('.test-tc').show();
		},
		// 提交考试
		subTest: function(data){
			var that = this;
			// operateScore:0,//操作得分
			// timeScore:0,//时间得分
			// allScore:0,//总得分
			var doRate = data.operateScore;//操作得分
			var useTime = that.useTimes > 0 ? that.useTimes : data.useTime;//使用时间
			var is_zero = data.is_zero;//是否操作总分为0
			let hand = data.type == '0x03' ? 'both' : data.hand;
			let hit_error_times = data.type == '0x03' ? data.errorTimes : '';
			let extend  = {hand: hand,left_hit_error_times:'',right_hit_error_times:''}

			if(data.type == '0x03'){
				extend.left_hit_error_times  = data.leftErrorTimes || 0 ;
				extend.right_hit_error_times = data.rightErrorTimes || 0 ;
			}

			var params = {
				log_id: that.testData.id,//考试当前id
				do_point: doRate,//操作得分比例
				time:useTime,//操作用时秒
				is_zero:is_zero,//1总分为0
				extend: JSON.stringify(extend),
				hit_error_times: hit_error_times,//飞越龙门触碰错误次数
			}
			
			// console.log('提交考试结果接口....' + JSON.stringify(params))
			APP.r.post({
				api: 'exam/submit_exam_log',
				params:params,
				success: function(res) {
					if(data.type == '0x03'){
						res.data.type = data.type
						res.data.errorTimes = data.errorTimes
						res.data.leftErrorTimes = data.leftErrorTimes
						res.data.rightErrorTimes = data.rightErrorTimes
					}
					// let allData = {...data,...res.data}
					that.testEnd(res.data);//弹窗
					// 刷新考试结果
					api.sendEvent({
						name: 'Newest_ExamLog',
						extra: {}
					});
				}
			});
		},
	}
}
API.run(page);
